﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.VersionControl.Client;

namespace RenameTracker
{
    public class TFS
    {
        public TFS(string serverName) 
        {
            var tfs = new TeamFoundationServer(serverName, new UICredentialsProvider());
            tfs.EnsureAuthenticated();
            _vc = (VersionControlServer)tfs.GetService(typeof(VersionControlServer));
        }

        public TFS(VersionControlServer vc)
        {
            _vc = vc;
        }

        private VersionControlServer _vc;

        public IEnumerable<ChangeInfoExplained> GetNamespaceHistory(Item item, bool showDeletes)
        {
            var history = _vc.QueryHistory(item.ServerItem, new ChangesetVersionSpec(item.ChangesetId), item.DeletionId, RecursionType.None,
                                           null, new ChangesetVersionSpec(1), VersionSpec.Latest, Int32.MaxValue, true, false);

            ChangeType namespaceChanges = ChangeType.Add | ChangeType.Branch | ChangeType.Rename;
            ChangeType deleteChanges = ChangeType.Delete | ChangeType.Undelete;
            ChangeType filteredChanges = showDeletes ? namespaceChanges | deleteChanges : namespaceChanges;
                        
            return from Changeset c in history
                   where c.Changes[0].ChangeType.IsType(filteredChanges)
                   select new ChangeInfoExplained(c);
        }

        public IDictionary<int, Item> GetSlotHistoryUnique(string path)
        {
            var slotHistory = _vc.QueryHistory(path, VersionSpec.Latest, 0, RecursionType.None, null, null, null,
                                               Int32.MaxValue, true, true);

            var items = new Dictionary<int, Item>();
            foreach (Changeset change in slotHistory)
            {
                items.Add(change.Changes[0].Item.ItemId, change.Changes[0].Item);
            }           
            
            return items;
        }
    }
}
